import { EventKeyboard, Input, input, KeyCode } from 'cc';
import { Observable, Observer } from "rxjs";

export function KeyUp() {
    return new Observable((observer: Observer<KeyCode>) => {
        const onKeyUp = (event: EventKeyboard) => {
            observer.next(event.keyCode);
        };
        input.on(Input.EventType.KEY_UP, onKeyUp, this);
        return () => {
            input.off(Input.EventType.KEY_UP, onKeyUp, this);
        }
    });
}

export function KeyDown() {
    return new Observable((observer: Observer<KeyCode>) => {
        const onKeyDown = (event: EventKeyboard) => {
            observer.next(event.keyCode);
        };
        input.on(Input.EventType.KEY_DOWN, onKeyDown, this);
        return () => {
            input.off(Input.EventType.KEY_DOWN, onKeyDown, this);
        }
    });
}

export function KeyDownUp() {
    return new Observable((observer: Observer<EventKeyboard>) => {
        const onKeyDown = (event: EventKeyboard) => observer.next(event);
        const onKeyUp = (event: EventKeyboard) => observer.next(event);
        input.on(Input.EventType.KEY_DOWN, onKeyDown, this);
        input.on(Input.EventType.KEY_UP, onKeyUp, this);
        return () => {
            input.off(Input.EventType.KEY_DOWN, onKeyDown, this);
            input.off(Input.EventType.KEY_UP, onKeyUp, this);
        }
    });
}